import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:photo_frame/net/model/member_model.dart';
import 'package:photo_frame/provider/users_provider.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:photo_frame/widgets/custom_cupertino_alert_dialog.dart';
import 'package:provider/provider.dart';

class EditMemberDialog extends StatefulWidget {
  Map<String, dynamic> args;

  EditMemberDialog(this.args, {super.key});

  @override
  State<StatefulWidget> createState() => _EditMemberDialogState();
}

class _EditMemberDialogState extends State<EditMemberDialog> {
  bool isEdit = false;
  String? _frameId;

  MemberModel _editMemberModel = MemberModel();

  TextEditingController nameController = TextEditingController();
  TextEditingController emailController = TextEditingController();
  EditMemberViewModel vm = EditMemberViewModel();

  @override
  void initState() {
    super.initState();
    _frameId = widget.args["frameId"];
    var member = widget.args["member"];
    if (member != null) {
      isEdit = true;
      _editMemberModel.updateWithModel(MemberModel.fromMap(member));
      vm.selectColor(vm._colors.indexOf(Color(_editMemberModel.fixedColor)));
    }
    nameController.text = _editMemberModel.name ?? "";
    emailController.text = _editMemberModel.email ?? "";
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    vm.init(context);
  }

  @override
  void dispose() {
    super.dispose();
    nameController.dispose();
    emailController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return CustomCupertinoAlertDialog(
      title: Text(
        AppLocalizationsWrapper.instance.unwrap(context).memberEdit,
        style: TextStyle(
            fontSize: 16,
            color: Color(0xff333333),
            fontWeight: FontWeight.bold),
      ),
      content: ChangeNotifierProvider(
        create: (BuildContext context) => vm,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.only(left: 11),
              child: Text(
                AppLocalizationsWrapper.instance
                    .unwrap(context)
                    .editMemberDialogNickname,
                style: TextStyle(
                    color: Color(0xff333333),
                    fontSize: 14,
                    fontWeight: FontWeight.bold),
              ),
            ),
            SizedBox(
              height: 13,
            ),
            Container(
              height: 44,
              padding: EdgeInsets.symmetric(horizontal: 14),
              decoration: BoxDecoration(
                color: Color(0xffEAECEE),
                borderRadius: BorderRadius.circular(10.0),
              ),
              alignment: Alignment.centerLeft,
              child: TextField(
                maxLines: 1,
                minLines: 1,
                controller: nameController,
                style: TextStyle(fontWeight: FontWeight.normal, fontSize: 16),
                decoration: InputDecoration(
                  isDense: true,
                  hintMaxLines: 1,
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.all(0),
                  hintText: AppLocalizationsWrapper.instance
                      .unwrap(context)
                      .editMemberDialogNicknameHint,
                  hintStyle: TextStyle(
                    color: Colors.grey,
                    fontSize: 16,
                  ),
                ),
              ),
            ),
            SizedBox(
              height: 11,
            ),
            Row(
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 11),
                  child: Text(
                    AppLocalizationsWrapper.instance
                        .unwrap(context)
                        .editMemberDialogBindEmail,
                    style: TextStyle(
                        color: Color(0xff333333),
                        fontSize: 14,
                        fontWeight: FontWeight.bold),
                  ),
                ),
                SizedBox(width: 10),
                Text(
                  AppLocalizationsWrapper.instance
                      .unwrap(context)
                      .editMemberDialogBindEmailTips,
                  style: TextStyle(color: Color(0xff666666), fontSize: 10),
                ),
              ],
            ),
            SizedBox(height: 13),
            Container(
              height: 44,
              padding: EdgeInsets.symmetric(horizontal: 14),
              decoration: BoxDecoration(
                  color: Color(0xffEAECEE),
                  borderRadius: BorderRadius.circular(10.0)),
              alignment: Alignment.centerLeft,
              child: TextField(
                maxLines: 1,
                minLines: 1,
                controller: emailController,
                style: TextStyle(fontWeight: FontWeight.normal, fontSize: 16),
                decoration: InputDecoration(
                  isDense: true,
                  hintMaxLines: 1,
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.all(0),
                  hintText: AppLocalizationsWrapper.instance
                      .unwrap(context)
                      .editMemberDialogBindEmailHint,
                  hintStyle: TextStyle(
                    color: Colors.grey,
                    fontSize: 16,
                  ),
                ),
              ),
            ),
            SizedBox(height: 21),
            Padding(
              padding: const EdgeInsets.only(left: 11),
              child: Text(
                AppLocalizationsWrapper.instance
                    .unwrap(context)
                    .editMemberDialogBindColor,
                style: TextStyle(
                    color: Color(0xff333333),
                    fontSize: 14,
                    fontWeight: FontWeight.bold),
              ),
            ),
            SizedBox(height: 14.5),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 11),
              child: Selector<EditMemberViewModel, int>(
                shouldRebuild: (n1, n2) => n1 != n2,
                selector: (_, vm) => vm._selectedColorIdx,
                builder: (BuildContext context, int value, Widget? child) {
                  return GridView.builder(
                    itemCount: vm._colors.length,
                    shrinkWrap: true,
                    padding: EdgeInsets.zero,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 6,
                      childAspectRatio: 1.0,
                      crossAxisSpacing: 20,
                      mainAxisSpacing: 20,
                    ),
                    itemBuilder: (BuildContext context, int index) {
                      return CupertinoButton(
                        padding: EdgeInsets.zero,
                        onPressed: () {
                          vm.selectColor(index);
                        },
                        child: Container(
                          width: 53,
                          height: 53,
                          decoration: BoxDecoration(
                              color: vm._colors[index], shape: BoxShape.circle),
                          child: Visibility(
                              visible: index == vm._selectedColorIdx,
                              child: Icon(
                                Icons.check,
                                color: Colors.white,
                                size: 18,
                              )),
                        ),
                      );
                    },
                  );
                },
              ),
            ),
            SizedBox(height: 18.5),
          ],
        ),
      ),
      actions: <Widget>[
        CupertinoButton(
          padding: EdgeInsets.zero,
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text(
            AppLocalizationsWrapper.instance.unwrap(context).cancel,
            style: TextStyle(
                fontSize: 16,
                color: Color(0xff333333),
                fontWeight: FontWeight.bold),
          ),
        ),
        CupertinoButton(
          padding: EdgeInsets.zero,
          onPressed: () async {
            var arguments = _editMemberModel
              ..name = nameController.text
              ..email = emailController.text
              ..color = vm._colors[vm._selectedColorIdx].value;
            var succeed =
                await vm.submit(context, _frameId ?? "", isEdit, arguments);
            if (succeed) {
              ARouter.instance.pagePop(arguments: arguments);
            }
          },
          child: Text(
            AppLocalizationsWrapper.instance.unwrap(context).confirm,
            style: TextStyle(
                fontSize: 16,
                color: Color(0xff3F74EF),
                fontWeight: FontWeight.bold),
          ),
        ),
      ],
    );
  }
}

Color DEFAULT_COLOR = Color(0xffFF6F6F);

class EditMemberViewModel extends ChangeNotifier {
  late UsersViewModel _usersViewModel;
  final List<Color> _colors = [
    Color(0xffFF6F6F),
    Color(0xffD68ACD),
    Color(0xffFFA23A),
    Color(0xff8EBA95),
    Color(0xff87CF45),
    Color(0xffA97FD9),
    Color(0xffEAD107),
    Color(0xff66C1FF),
    Color(0xff4B90FF),
    Color(0xff6E779F),
    Color(0xffA7BBBD),
    Color(0xff696969),
  ];
  int _selectedColorIdx = 0;

  init(BuildContext context) {
    _usersViewModel = context.read<UsersViewModel>();
  }

  selectColor(int idx) {
    _selectedColorIdx = idx == -1 ? 0 : idx;
    notifyListeners();
  }

  Future<bool> submit(BuildContext context, String frameId, bool isEdit,
      MemberModel memberModel) async {
    if (memberModel.name?.isNotEmpty != true) {
      Fluttertoast.showToast(
          msg: AppLocalizationsWrapper.instance
              .unwrap(context)
              .editMemberDialogNicknameHint);
      return false;
    }
    await EasyLoading.show(
      maskType: EasyLoadingMaskType.black,
    );
    if (memberModel.id == null) {
      return await _usersViewModel.add(frameId, memberModel).whenComplete(() {
        EasyLoading.dismiss();
      });
    } else {
      return await _usersViewModel.update(frameId, memberModel).whenComplete(() {
        EasyLoading.dismiss();
      });
    }
  }
}
